package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.SaveTimeLine;
import com.tanhua.model.domain.PageResult;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class MovementsApiImpl implements MovementsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private SaveTimeLine saveTimeLine;



    /**
     * 发布动态
     */
    public void publishMoments(Movement movement) {

        try {

            //1.把用户发布的动态内容保存到动态详情表
            //1.1先设置pid
            movement.setPid(idWorker.getNextId("movement"));
            //1.2再设置动态的发布时间
            movement.setCreated(System.currentTimeMillis());
            //1.3调用mongotemplate保存到动态详情表
            mongoTemplate.save(movement);


            //2.查询当前登录用户的所有好友和遍历当前用户的好友
            //一个好友1创建一个时间线对象
            saveTimeLine.saveTimeLine(movement.getUserId(), movement.getId());




/*
            Thread.sleep(10000);

            //2.查询当前登录用户的所有好友
            Criteria criteria = Criteria.where("userId").is(movement.getUserId());
            Query query = Query.query(criteria);
            List<Friend> friends = mongoTemplate.find(query, Friend.class);


            //3.遍历当前用户的好友
            for (Friend friend : friends) {
                //创建时间线表
                MovementTimeLine mtl = new MovementTimeLine();
                mtl.setUserId(friend.getUserId());
                mtl.setFriendId(friend.getFriendId());
                mtl.setMovementId(movement.getId());
                mtl.setCreated(System.currentTimeMillis());

                //保存到时间线表
                mongoTemplate.save(mtl);
            }*/
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    /**
     *查看我的朋友圈
     */
    public PageResult lookMYMoments(Integer page, Integer pagesize, Long userId) {

        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);

        query.skip((page - 1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));

        List<Movement> movements = mongoTemplate.find(query, Movement.class);


        PageResult pageResult = new PageResult(page,pagesize, 0,movements);


        return pageResult;
    }


    /**
     *查看好友动态
     */
    public List<Movement> viewSocialUpdates(Long friendId, Integer page, Integer pageSize) {

        //1.根据用户id查询时间线表

        //1.1创建Criteria对象，构造查询条件
        Criteria criteria = Criteria.where("friendId").is(friendId);
        //1.2根据Criteria创建Query对象
        Query query = Query.query(criteria)
                .skip((page - 1) * pageSize)
                .limit(pageSize).with(Sort.by(Sort.Order.desc("created")));

        List<MovementTimeLine> timeLines = mongoTemplate.find(query, MovementTimeLine.class);


        //2.在时间线表批量获取动态详情的id
        //这个list集合装的是好友的动态详情id
        List<ObjectId> movementIds = CollUtil.getFieldValues(timeLines, "movementId", ObjectId.class);

        //3.根据动态详情id查询动态

        Criteria criteria1 = Criteria.where("id").in(movementIds);
        Query query1 = Query.query(criteria1);

        List<Movement> movements = mongoTemplate.find(query1, Movement.class);

        return movements;

    }



    /**
     *  大数据推荐系统没有推荐的动态详情，自己随机推荐，保证用户使用体验
     */
    public List<Movement> randomMoments(Integer pageSize) {

        //
        TypedAggregation<Movement> aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(pageSize));

        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);

        List<Movement> mappedResults = results.getMappedResults();
        return mappedResults;
    }

    /**
     *   大数据系统根据用户的行为特征计算出要推送给用户的动态详情
     */
    public List<Movement> lookRecommendMoments(List<Long> longPids) {
        //1.创建Criteria对象，设置查询条件,根据pid查询动态详情表
        Criteria criteria = Criteria.where("pid").in(longPids);
        //2.根据criteria创建Query对象
        Query query = Query.query(criteria);

        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return movements;
    }


    /**
     *
     *查询单条动态
     */
    public Movement lookOneMoment(String movementId) {

        Movement movement = mongoTemplate.findById(movementId, Movement.class);
        return movement;
    }

}

